package com.bookkeeping.bookkeepingapi.service;

import com.bookkeeping.bookkeepingapi.model.User;
import com.bookkeeping.bookkeepingapi.repository.BookKeepRepository;
import com.bookkeeping.bookkeepingapi.repository.UserRepository;
import com.bookkeeping.bookkeepingapi.service.util.MD5Util;
import com.bookkeeping.bookkeepingapi.web.vm.UserVM;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BookKeepRepository bookKeepRepository;
    @Transactional
    public User create(UserVM userVM) {
        //将userVM变成user
        User user = new User(userVM);
        //设置密码
        user.setPassword(MD5Util.MD5(userVM.getPassword()));
        return userRepository.save(user);
    }

    @Transactional
    public User update(User user,UserVM userVM){
        user.setRealname(userVM.getRealname());
        return userRepository.save(user);
    }
    @Transactional
    public void delete(User user) {
        bookKeepRepository.deleteByUser(user);
        userRepository.delete(user);
    }
}
